package com.ruoyi.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.vo.*;
import com.ruoyi.mapper.GoodsEvaluateVoMapper;
import com.ruoyi.service.IUserCenterService;
import com.ruoyi.mapper.UserCenterMapper;
import com.ruoyi.system.domain.*;
import com.ruoyi.utils.TanpuhuiUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserCenterServiceImpl implements IUserCenterService {
    @Autowired
    private UserCenterMapper userCenterMapper;
    @Autowired
    private TanpuhuiUtils tanpuhuiUtils;
    @Autowired
    private GoodsEvaluateVoMapper goodsEvaluateVoMapper;

    /**
     * 查询用户信息
     *
     * @param account 用户账号
     * @return 用户信息
     */
    @Override
    public UserInfoVo selectUserInfoByAccount(String account) {
        UserInfoVo userInfoVo =  userCenterMapper.selectUserInfoByAccount(account);
        if (userInfoVo != null) {
            userCenterMapper.updateTitleCode(userInfoVo.getUserId(),userInfoVo.getCo2Reduce());
        }
        return userInfoVo;
    }

    @Override
    public UserInfoVo selectUserInfoByOpenid(String openid) {
        return userCenterMapper.selectUserInfoByOpenid(openid);
    }


    @Override
    public UserInfoVo selectUserInfoByWechat(String wechat) {
        return userCenterMapper.selectUserInfoByWechat(wechat);
    }

    /**
     * 修改用户信息管理
     *
     * @param userInfo 用户Id
     * @return 结果
     */
    @Override
    public int updateUserInfo(UserInfo userInfo) {
        userInfo.setUpdateTime(DateUtils.getNowDate());
        return userCenterMapper.updateUserInfo(userInfo);
    }

    /**
     * 查询低碳行为记录
     *
     * @param userId 用户Id
     * @return 低碳行为记录
     */
    @Override
    public List<BehaviorRecode> selectBehaviorByUserID(Long userId, Long pageNum, Long pageSize)
    {
        Long offset = (pageNum - 1) * pageSize;
        return userCenterMapper.selectBehaviorByUserID(userId, offset, pageSize);
    }

    /**
     * 查询低碳活动记录
     *
     * @param userId 用户Id
     * @return 低碳活动记录
     */
    @Override
    public List<ActivityLogs> selectActivityLogsByUserID(Long userId, Long pageNum, Long pageSize) {
        Long offset = (pageNum - 1) * pageSize;
        return userCenterMapper.selectActivityLogsByUserID(userId, offset, pageSize);
    }

    /**
     * 查询地址信息
     *
     * @param userId 用户Id
     * @return 用户地址信息
     */
    @Override
    public List<Address> selectAddressByUserId(Long userId) {
        return userCenterMapper.selectAddressByUserId(userId);
    }

    /**
     * 根据减碳量排名获取用户信息列表
     * @return 用户信息列表
     */
    @Override
    public List<UserInfoVo> selectUserInfoByReduceCo2() {
        return userCenterMapper.selectUserInfoByReduceCo2();
    }

    /**
     * 根据日减碳量排名获取用户信息列表
     * @param pageNum 页码
     * @param pageSize 页大小
     * @return 用户信息列表
     */
    @Override
    public List<UserInfoVo> getUserInfoByReduceCo2Day(Long pageNum, Long pageSize) {
        Long offset = (pageNum - 1) * pageSize;
        return userCenterMapper.getUserInfoByReduceCo2Day(offset, pageSize);
    }

    /**
     * 根据月减碳量排名获取用户信息列表
     * @param pageNum 页码
     * @param pageSize 页大小
     * @return 用户信息列表
     */
    @Override
    public List<UserInfoVo> getUserInfoByReduceCo2Month(Long pageNum, Long pageSize) {
        Long offset = (pageNum - 1) * pageSize;
        return userCenterMapper.getUserInfoByReduceCo2Month(offset, pageSize);
    }

    /**
     * 根据减碳量排名获取组织信息列表
     * @param pageNum 页码
     * @param pageSize 页大小
     * @return 组织信息列表
     */
    @Override
    public List<OrganizationVo> selectOrganizationList(Long pageNum, Long pageSize) {
        Long offset = (pageNum - 1) * pageSize;
        return userCenterMapper.selectOrganizationList(offset, pageSize);
    }

    /**
     * 根据日减碳量排名获取组织信息列表
     * @param pageNum 页码
     * @param pageSize 页大小
     * @return 组织信息列表
     */
    @Override
    public List<OrganizationVo> selectOrganizationListDay(Long pageNum, Long pageSize) {
        Long offset = (pageNum - 1) * pageSize;
        return userCenterMapper.selectOrganizationListDay(offset, pageSize);
    }

    /**
     * 根据月减碳量排名获取组织信息列表
     * @param pageNum 页码
     * @param pageSize 页大小
     * @return 组织信息列表
     */
    @Override
    public List<OrganizationVo> selectOrganizationListMonth(Long pageNum, Long pageSize) {
        Long offset = (pageNum - 1) * pageSize;
        return userCenterMapper.selectOrganizationListMonth(offset, pageSize);
    }

    @Override
    public String getPointsRule(){
        return userCenterMapper.getPointsRule();
    }

    @Override
    public List<UserInfoVo> getUserList(){
        return userCenterMapper.getUserList();
    }

    @Override
    public void updateDefaultAddress(Long userId, Long addressId){
        userCenterMapper.updateDefaultAddress(userId, addressId);
    }

    /**
     * 根据用户ID获取待付款订单列表
     * @param userId 用户ID
     * @return 个人订单列表
     */
    @Override
    public List<NoPayOrderVo> selectNoPayOrder(Long userId, Long pageNum, Long pageSize) {
        // 删除超时的订单
        userCenterMapper.deleteTimeoutOrder();
        Long offset = null;
        if (pageNum != null && pageSize != null){
            offset = (pageNum - 1) * pageSize;
        }
        List<OrderInfo> orderInfoList = userCenterMapper.getOrderInfoList(userId, offset, pageSize);
        List<NoPayOrderVo> orderList = new ArrayList<NoPayOrderVo>();
//        System.out.println(orderInfoList);
        for (OrderInfo orderInfo : orderInfoList){
            if (Objects.equals(orderInfo.getPayState(), "待付款")){
                NoPayOrderVo noPayOrderVo = new NoPayOrderVo();
                noPayOrderVo.setOrderId(orderInfo.getOrderId());
                noPayOrderVo.setPayState(orderInfo.getPayState());
                noPayOrderVo.setOrderPrice(orderInfo.getOrderPrice());
                noPayOrderVo.setOrderPrice(orderInfo.getOrderPrice());
                noPayOrderVo.setCreateTime(orderInfo.getCreateTime());
                List<Map<String, Object>> orderItemMapList = userCenterMapper.selectOrderItemByOrderId(orderInfo.getOrderId());
                for (Map<String, Object> orderItemMap : orderItemMapList){
//                    System.out.println(orderItemMap.get("shopName"));
                    if (noPayOrderVo.getOrderItemList() == null) {
                        noPayOrderVo.setOrderItemList(new HashMap<String, Object>());
                    }
                    if (!noPayOrderVo.getOrderItemList().containsKey(orderItemMap.get("shopName"))){
                        Map<String, Object> orderItem = new HashMap<>();
                        noPayOrderVo.getOrderItemList().put((String) orderItemMap.get("shopName"), new ArrayList<Map<String, Object>>());
                    }
                    if (Objects.equals(orderItemMap.get("saleMode"), "售卖品")){
                        // 获取对应 shopName 的列表并添加当前的订单项
                        List<Map<String, Object>> shopOrderItems = (List<Map<String, Object>>) noPayOrderVo.getOrderItemList().get(orderItemMap.get("shopName"));
                        System.out.println("stander:" + (String) orderItemMap.get("stander"));
                        int StanderIndex = tanpuhuiUtils.getStanderIndex((String) orderItemMap.get("stander"), Long.parseLong(orderItemMap.get("goodsId").toString()));
                        System.out.println("standerIndex:" + StanderIndex);
                        if (orderItemMap.get("relateGoodsId") != null && !orderItemMap.get("relateGoodsId").toString().isEmpty()) {
                            System.out.println(orderItemMap.get("relateGoodsId"));
                            String[] relateGoodsIdList = orderItemMap.get("relateGoodsId").toString().split("/");
//                            System.out.println(Arrays.toString(relateGoodsIdList));
//                            System.out.println(orderItemMap.get("relateGoodsId").toString());
                            List<Map<String, Object>> relateGoodsList = new ArrayList<Map<String, Object>>();
                            for (String relateGoodsId : relateGoodsIdList) {
                                relateGoodsList.add(userCenterMapper.selectRelateGoods(relateGoodsId));
                            }
                            orderItemMap.put("relateGoodsList", relateGoodsList);
                        }
                        else {
                            orderItemMap.put("relateGoodsList", null);
                        }
                        shopOrderItems.add(orderItemMap);
                    }
                }
//            System.out.println(noPayOrderVo.getOrderItemList());
                orderList.add(noPayOrderVo);
            }
        }
        return orderList;
    }

    @Override
    public List<PayedOrderVo> selectPayedOrder(Long userId, Long pageNum, Long pageSize, String goodsName){
        Long offset = (pageNum - 1) * pageSize;
        List<PayedOrderVo> payedOrderVoList = userCenterMapper.selectPayedOrder(userId, offset, pageSize, goodsName);
        for (PayedOrderVo payedOrderVo : payedOrderVoList){
//            System.out.println(payedOrderVo.getCreateTime());
            if (payedOrderVo.getRelateGoodsId() != null && !payedOrderVo.getRelateGoodsId().isEmpty()){
                String[] relateGoodsIdList = payedOrderVo.getRelateGoodsId().split("/");
                List<Map<String, Object>> relateGoodsList = new ArrayList<Map<String, Object>>();
                for (String relateGoodsId : relateGoodsIdList) {
                    relateGoodsList.add(userCenterMapper.selectRelateGoods(relateGoodsId));
                }
                payedOrderVo.setRelateGoodsList(relateGoodsList);
            }
        }
        return payedOrderVoList;
    }

    @Override
    public Map<String, Object> selectOrderByGoodsName(Long userId, String goodsName, Long pageNum, Long pageSize){
        Map<String, Object> resultMap = new HashMap<>();
        Long offset = (pageNum - 1) * pageSize;
        List<NoPayOrderVo> noPayOderList = new ArrayList<>();
        List<PayedOrderVo> payedOrderVoList = new ArrayList<>();
        // 通过商品名称查询待付款订单号
        List<OrderInfo> noPayOrderInfoList = userCenterMapper.selectNoPayOrderByGoodsName(userId, goodsName);
        for (OrderInfo orderInfo : noPayOrderInfoList){
            NoPayOrderVo noPayOrderVo = new NoPayOrderVo();
            noPayOrderVo.setOrderId(orderInfo.getOrderId());
            noPayOrderVo.setPayState(orderInfo.getPayState());
            noPayOrderVo.setOrderPrice(orderInfo.getOrderPrice());
            noPayOrderVo.setOrderPrice(orderInfo.getOrderPrice());
            noPayOrderVo.setCreateTime(orderInfo.getCreateTime());
            List<Map<String, Object>> orderItemMapList = userCenterMapper.selectOrderItemByOrderId(orderInfo.getOrderId());
            for (Map<String, Object> orderItemMap : orderItemMapList){
//                    System.out.println(orderItemMap.get("shopName"));
                if (noPayOrderVo.getOrderItemList() == null) {
                    noPayOrderVo.setOrderItemList(new HashMap<String, Object>());
                }
                if (!noPayOrderVo.getOrderItemList().containsKey(orderItemMap.get("shopName"))){
                    Map<String, Object> orderItem = new HashMap<>();
                    noPayOrderVo.getOrderItemList().put((String) orderItemMap.get("shopName"), new ArrayList<Map<String, Object>>());
                }
                if (Objects.equals(orderItemMap.get("saleMode"), "售卖品")){
                    // 获取对应 shopName 的列表并添加当前的订单项
                    List<Map<String, Object>> shopOrderItems = (List<Map<String, Object>>) noPayOrderVo.getOrderItemList().get(orderItemMap.get("shopName"));
                    System.out.println("stander:" + (String) orderItemMap.get("stander"));
                    int StanderIndex = tanpuhuiUtils.getStanderIndex((String) orderItemMap.get("stander"), Long.parseLong(orderItemMap.get("goodsId").toString()));
                    System.out.println("standerIndex:" + StanderIndex);
                    orderItemMap.replace("goodsDiscount", orderItemMap.get("goodsDiscount").toString().split("/")[StanderIndex]);
                    orderItemMap.replace("goodsPrice", orderItemMap.get("goodsPrice").toString().split("/")[StanderIndex]);
//                    System.out.println(orderItemMap.get("relateGoodsId"));
                    if (orderItemMap.get("relateGoodsId") != null && !orderItemMap.get("relateGoodsId").toString().isEmpty()) {
                        String[] relateGoodsIdList = orderItemMap.get("relateGoodsId").toString().split("/");
                        List<Map<String, Object>> relateGoodsList = new ArrayList<Map<String, Object>>();
                        for (String relateGoodsId : relateGoodsIdList) {
                            relateGoodsList.add(userCenterMapper.selectRelateGoods(relateGoodsId));
                        }
                        orderItemMap.put("relateGoodsList", relateGoodsList);
                    }
                    else {
                        orderItemMap.put("relateGoodsList", null);
                    }
                    shopOrderItems.add(orderItemMap);
                }
            }
//            System.out.println(noPayOrderVo.getOrderItemList());
            noPayOderList.add(noPayOrderVo);
        }
        // 通过商品名称查询已付款订单项号
        payedOrderVoList = userCenterMapper.selectPayedOrder(userId, offset, pageSize, goodsName);
        for (PayedOrderVo payedOrderVo : payedOrderVoList){
//            System.out.println(payedOrderVo.getCreateTime());
            if (payedOrderVo.getRelateGoodsId() != null && !payedOrderVo.getRelateGoodsId().isEmpty()){
                String[] relateGoodsIdList = payedOrderVo.getRelateGoodsId().split("/");
                List<Map<String, Object>> relateGoodsList = new ArrayList<Map<String, Object>>();
                for (String relateGoodsId : relateGoodsIdList) {
                    relateGoodsList.add(userCenterMapper.selectRelateGoods(relateGoodsId));
                }
                payedOrderVo.setRelateGoodsList(relateGoodsList);
            }
        }
        resultMap.put("noPayOderList", noPayOderList);
        resultMap.put("payedOrderVoList", payedOrderVoList);
        return resultMap;
    }

    @Override
    public Long getUserPoints(Long userId){
        return userCenterMapper.getUserPoints(userId);
    }

    @Override
    public Map<String, Object> getConversionRate(){
        String co2ReduceToPoints = userCenterMapper.getCo2ReduceToPoints();
        String co2ReduceToRMB = userCenterMapper.getCo2ReduceToRMB();
        String pointsToRMB = userCenterMapper.getPointsToRMB();
        Map<String, Object> conversionRate = new HashMap<>();
        conversionRate.put("co2ReduceToPoints", co2ReduceToPoints);
        conversionRate.put("co2ReduceToRMB", co2ReduceToRMB);
        conversionRate.put("pointsToRMB", pointsToRMB);
        return conversionRate;
    }

    @Override
    public void confirmReceipt(Long orderItemId){
        userCenterMapper.confirmReceipt(orderItemId);
    }

    @Override
    public void addGoodsEvaluate(GoodsEvaluate goodsEvaluate){
//        System.out.println(goodsEvaluate);
        goodsEvaluateVoMapper.addGoodsEvaluate(goodsEvaluate);
        System.out.println("goodsEvaluateVoMapper.addGoodsEvaluate(goodsEvaluate);" + goodsEvaluate.getOrderItemId());
        userCenterMapper.updateOrderItemEvaluateState(goodsEvaluate.getOrderItemId());
    }

    @Override
    public void updateGoodsEvaluate(GoodsEvaluate goodsEvaluate){
        goodsEvaluateVoMapper.updateGoodsEvaluate(goodsEvaluate);
    }

    @Override
    public  GoodsEvaluate getGoodsEvaluateByOrderItemId(Long orderItemId){
        return goodsEvaluateVoMapper.getGoodsEvaluateByOrderItemId(orderItemId);
    }

    @Override
    public void deleteGoodsEvaluateByOrderItemId(Long orderItemId){
        goodsEvaluateVoMapper.deleteGoodsEvaluateByOrderItemId(orderItemId);
        userCenterMapper.updateOrderItemEvaluateStateFalse(orderItemId);
    }

    @Override
    public void addRefund(Refund refund){
        userCenterMapper.addRefund(refund);
        // 更新退款商品数量
        userCenterMapper.updateOrderItemRefundCounts(refund.getOrderItemId());
    }

    @Override
    public Long getMaxRefundNum(Long orderItemId){
        return userCenterMapper.getMaxRefundNum(orderItemId);
    }

    @Override
    public List<Refund> getRefundRecordByOrderItemId(Long orderItemId){
        return userCenterMapper.getRefundRecordByOrderItemId(orderItemId);
    }

    @Override
    public Long selectActivityLogCountByUserID(Long userId){
        return userCenterMapper.selectActivityLogCountByUserID(userId);
    }

    @Override
    public Long selectBehaviorCountByUserID(Long userId){
        return userCenterMapper.selectBehaviorCountByUserID(userId);
    }

    @Override
    public List<OrderInfo> getOrderInfoList(Long userId, Long pageNum, Long pageSize){
        Long offset = (pageNum - 1) * pageSize;
        return userCenterMapper.getOrderInfoList(userId, offset, pageSize);
    }

    @Override
    public Long getOrderInfoCount(Long userId){
        return userCenterMapper.getOrderInfoCount(userId);
    }

    @Override
    public void insertUserInfo(UserInfoVo userInfo){
        userCenterMapper.insertUserInfo(userInfo);
    }

    @Override
    public Map<String, Object> getUserReduceCo2(Long userId){
        Double personalCo2Day = userCenterMapper.getUserReduceCo2Day(userId);
        Double personalCo2Month = userCenterMapper.getUserReduceCo2Month(userId);
        Double organizationCo2Day = userCenterMapper.getOrganizationReduceCo2Day(userId);
        Double organizationCo2Month = userCenterMapper.getOrganizationReduceCo2Month(userId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("personalCo2Day", personalCo2Day);
        resultMap.put("personalCo2Month", personalCo2Month);
        resultMap.put("organizationCo2Day", organizationCo2Day);
        resultMap.put("organizationCo2Month", organizationCo2Month);
        return resultMap;
    }

    @Override
    public void reSubmitRefund(Refund refund){
        userCenterMapper.reSubmitRefund(refund);
    }

    @Override
    public void deleteAddressByAddressId(Long addressId){
        userCenterMapper.deleteAddressByAddressId(addressId);
    }

    @Override
    public boolean hasPassword(Long userId){
        return userCenterMapper.hasPassword(userId);
    }

    @Override
    public String changePassword(Long userId, String originalPassword, String newPassword){
        if (hasPassword(userId)){
            if (userCenterMapper.checkPassword(userId, originalPassword)){
                userCenterMapper.changePassword(userId, newPassword);
                return "修改成功";
            }
            else {
                return "原密码错误";
            }
        }
        else {
            userCenterMapper.changePassword(userId, newPassword);
            return "设置成功";
        }
    }

    @Override
    public String getSessionKey(Long userId){
        return userCenterMapper.getSessionKey(userId);
    }

}
